<template>
  <div :class="`tinymce-editor theme_${theme} useFor_${useFor}`">
    <div :id="tinymceId"></div>
    <div class="btns">
      <el-button
        class="btn-sure"
        size="small"
        type="primary"
        @click="save"
      >
        {{ $demoi18n('btn.save') }}
      </el-button>
      <el-button
        class="button-cancel"
        size="small"
        @click="cancel"
      >
        {{ $demoi18n('btn.cancel') }}
      </el-button>
    </div>
  </div>
</template>
<script>
import { getLang } from '@/utils/lang.js';
import langCN from './lang/zh_CN.js';
import { xssValueFilter } from '@/utils/util';
import { getHelpManualBaseUrl } from '@/components/common/help-manual/help-manual-util.js';

// tinymce
import 'tinymce/tinymce.min';
import 'tinymce/models/dom';
import 'tinymce/themes/silver/theme.min.js';
import 'tinymce/icons/default/icons';
import 'tinymce/skins/ui/oxide/skin.css';
import 'tinymce/skins/ui/oxide/content.css';
import './skin/skin_dark.less';

// tinymce插件
import 'tinymce/plugins/lists/plugin.min.js';
import 'tinymce/plugins/quickbars/plugin.min.js';
import 'tinymce/plugins/table/plugin.min.js';

export default {
  components: {},
  props: {
    theme: {
      type: String,
      default: 'light',
    },
    tinymceOptions: {
      type: Object,
      default: () =>({}),
    },
    html: {
      type: String,
      default: '',
    },
    useFor: {
      type: String,
      default: 'tooltip', // tooltip或hover-text
    },
  },
  emits: ['save', 'cancel'],
  data() {
    return {
      tinymceId: `vue-tinymce-${Date.now()}${Math.floor(Math.random() * 1000)}`,
      content: '',
      editor: null,
      maxFontSize: 72,
    };
  },
  computed: {
    currentLang() {
      const lang = getLang().replace('-', '_');
      const langPackage = lang === 'zh_CN' ? langCN : '';
      return { lang, langPackage };
    },
    $tinymce() {
      return tinymce?.get(this.tinymceId);
    },
    contentStyle() {
      let style;
      if (this.useFor === 'tooltip') {
        style = 'body{ font-size:16px; color:#fff; background-color: rgba(34,34,34,.7); }';
      }
      if (this.useFor === 'hover-text') {
        style = 'body{ font-size:16px; }';
      }
      if (this.theme === 'dark') {
        style = 'body{ font-size:16px; color:#fff; }';
      }
      return style;
    },
  },
  watch: {
    html: {
      handler() {
        this.content = xssValueFilter(this.html);
        if (this.editor) {
          this.editor.setContent(this.content);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.changeLanguage();
    this.init();
  },
  methods: {
    init() {
      const cssLink = this.getContentCssLInk();
      const defaultOptions = {
        'selector': `#${this.tinymceId}`,
        'language': this.currentLang.lang,
        'file_picker_types': 'image',
        'min_height': 200,
        'plugins': [
          'lists ',
          'quickbars',
          'table',
        ],
        'toolbar': `
          fontfamily blocks fontsize | 
          bold italic underline strikethrough forecolor backcolor | 
          alignleft aligncenter alignright alignjustify lineheight | 
          numlist bullist outdent indent | 
          blockquote table removeformat
        `,

        // 'content_css': cssLink,
        'content_css': false,
        'skin': false,

        'content_style': this.contentStyle,
        'images_upload_url': false,
        'branding': false, // （隐藏右下角技术支持）
        'menu': {}, // （自定义菜单）
        'menubar': '', // （1级菜单）
        'quickbars_insert_toolbar': '', // [插入]快捷工具栏
        'statusbar': false, // （显示隐藏状态栏）
        'font_size_formats': this.getFontSizes(),
        'font_family_formats': this.getFontFamilies(),
        'indentation': '20px',
        'remove_trailing_brs': false, // 删除最尾的br
        setup: editor => {
          editor.on('init', () => {
            this.editor = editor;
            editor.setContent(this.content);
          });
        },
      };
      const initOptions = Object.assign({}, defaultOptions, this.tinymceOptions);
      tinymce.init(initOptions);
    },

    getFontSizes() {
      const arr = [];
      for (let i = 11; i <= this.maxFontSize; i++) {
        arr.push(`${i}px`);
      }
      return arr.join(' ');
    },

    getFontFamilies() {
      const families = {
        'Microsoft YaHei': 'Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif',
        '宋体': 'SimSun',
        '黑体': 'SimHei',
        '楷体': 'KaiTi',
        '幼圆': 'YouYuan',
        'Andale Mono': 'andale mono,times',
        'Arial': 'arial,helvetica,sans-serif',
        'Arial Black': 'arial black,avant garde',
        'Book Antiqua': 'book antiqua,palatino',
        'Comic Sans MS': 'comic sans ms,sans-serif',
        'Georgia': 'georgia,palatino',
        'Helvetica': 'helvetica',
        'Impact': 'impact,chicago',
        'Symbol': 'symbol',
        'Tahoma': 'tahoma,arial,helvetica,sans-serif',
        'Terminal': 'terminal,monaco',
        'Times New Roman': 'times new roman,times',
        'Trebuchet MS': 'trebuchet ms,geneva',
        'Verdana': 'verdana,geneva',
        'Webdings': 'webdings',
        'Wingdings': '',
        'wingdings,zapf dingbats': '',
        'Courier New': 'courier new,courier',
        'Consolas': 'Consolas',

      };
      const arr = [];
      Object.entries(families).map(([i]) => {
        arr.push(`${i}=${families[i]}`);
      });
      return arr.join('; ');
    },

    // 内容css链接放在帮助文档目录
    getContentCssLInk() {
      const baseUrl = getHelpManualBaseUrl();
      const link = `${baseUrl}/tinymce_css/content.css?t=${Date.now()}`;
      return link;
    },

    // 改变语言
    changeLanguage() {
      const { lang, langPackage } = this.currentLang;
      if (lang && langPackage) {
        tinymce.addI18n(lang, langPackage);
      }
    },

    getEditorHtml() {
      let html = this.editor.getContent();
      html = html.replace(/<i class="tinymce"><\/i>/, '');
      html = `<i class="tinymce"></i>${html}`;
      this.content = html;
    },

    save() {
      this.getEditorHtml();
      const html = xssValueFilter(this.content);
      this.$emit('save', html);
    },

    cancel() {
      this.getEditorHtml();
      this.$emit('cancel', this.content);
    },
  },
};
</script>
<style lang="less" scoped>
.tinymce-editor{
  .btns {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .el-button {
      width: 60px;
      height: 32px;
    }
  }
  :deep(.tox-tbtn--select){
    width: 66px;
    &:first-child{
      width: auto;
    }
  }
  :deep(.tox-promotion){
    display: none;
  }
}
</style>
<style lang="less">
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
